package com.gy.api.pc.movie.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.gy.api.base.Constants;
import com.gy.api.base.IDEntity;
import com.gy.api.base.Type;
import com.gy.api.mobile.company.dao.CompanyInfoDao;
import com.gy.api.mobile.company.domain.po.CompanyInfoPO;
import com.gy.api.mobile.msg.dao.UserMessagesDao;
import com.gy.api.pc.examine.dao.ExamineDao;
import com.gy.api.pc.examine.dao.ExamineLogDao;
import com.gy.api.pc.examine.domain.po.ExamineLogPO;
import com.gy.api.pc.examine.domain.po.ExaminePO;
import com.gy.api.pc.examine.domain.vo.*;
import com.gy.api.pc.examine.service.IExamineService;
import com.gy.api.pc.filings.domain.po.PatentApplicationPO;
import com.gy.api.pc.filings.domain.vo.CulvertApprovalCompanyVo;
import com.gy.api.pc.filings.domain.vo.WcContentExamineListVO;
import com.gy.api.pc.movie.dao.WcContentExamineAncillaryDao;
import com.gy.api.pc.movie.dao.WcContentExamineDao;
import com.gy.api.pc.movie.domain.po.WcContentExamineAncillaryPO;
import com.gy.api.pc.movie.domain.po.WcContentExaminePO;
import com.gy.api.pc.movie.domain.vo.*;
import com.gy.api.pc.movie.service.IWcContentExamineService;
import com.gy.api.pc.sys.user.dao.SysUserDao;
import com.gy.api.pc.sys.user.domain.po.SysUserPO;
import com.gy.api.video.dao.ResourceFileDao;
import com.gy.api.video.domain.po.ResourceFilePO;
import com.gy.exception.BusinessException;
import com.gy.task.UserMessageThread;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class WcContentExamineServiceImpl implements IWcContentExamineService {
    @Autowired
    ExamineDao examineDao;
    @Autowired
    ExamineLogDao examineLogDao;
    @Autowired
    private IExamineService examineService;
    @Autowired
    WcContentExamineDao wcContentExamineDao;
    @Autowired
    WcContentExamineAncillaryDao wcContentExamineAncillaryDao;
    @Autowired
    private CompanyInfoDao companyInfoDao;
    @Autowired
    ResourceFileDao fileDao;
    @Override
    public void addSave(WcContentExamineSaveVO saveVO) {
        WcContentExaminePO wcContentExaminePO=new WcContentExaminePO();
        BeanUtils.copyProperties(saveVO, wcContentExaminePO);
        wcContentExaminePO.preInsert();
        wcContentExamineDao.insertSelective(wcContentExaminePO);
        WcContentExamineAncillaryPO wcContentExamineAncillaryPO=new WcContentExamineAncillaryPO();
        BeanUtils.copyProperties(saveVO, wcContentExamineAncillaryPO);
        wcContentExamineAncillaryPO.setWcContentExamineId(wcContentExaminePO.getId());

        if(StringUtils.isNotBlank(saveVO.getAncillaryFileCode())){
            Example fileExample=new Example(ResourceFilePO.class);
            fileExample.and().andEqualTo("fileKey",saveVO.getAncillaryFileCode());
            ResourceFilePO resourceFilePO=fileDao.selectOneByExample(fileExample);
            if(resourceFilePO==null){
                throw new BusinessException(Type.FAIL.getCode(),"影片编码不存在！");
            }
            wcContentExamineAncillaryPO.setAncillary4Name(resourceFilePO.getFileName());
            wcContentExamineAncillaryPO.setAncillary4Url(resourceFilePO.getFileFullPath());
        }
        wcContentExamineAncillaryDao.insertSelective(wcContentExamineAncillaryPO);

        //添加流程
        CompanyInfoPO companyInfoPO=companyInfoDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
        examineService.addExamineState(new ExamineAddVO(wcContentExaminePO.getId(), Constants.EXAMINE_MOVIE_LETTER[1],Constants.EXAMINE_1_USER,Constants.EXAMINE_TYPE_MOVIE_FILING
                ,companyInfoPO.getId(),companyInfoPO.getUserName()),saveVO.getIsOutbox().equals("0")?1:0);
    }

    @Override
    public void updateSave(WcContentExamineUpdateVO saveVO) {
        WcContentExaminePO wcContentExaminePO=wcContentExamineDao.selectByPrimaryKey(saveVO.getId());
        BeanUtils.copyProperties(saveVO, wcContentExaminePO);
        wcContentExaminePO.preUpdate();
        wcContentExamineDao.updateByPrimaryKeySelective(wcContentExaminePO);
        WcContentExamineAncillaryPO wcContentExamineAncillaryPO=wcContentExamineAncillaryDao.selectByPrimaryKey(wcContentExaminePO.getId());
        BeanUtils.copyProperties(saveVO, wcContentExamineAncillaryPO);
        if(StringUtils.isNotBlank(saveVO.getAncillaryFileCode())){
            Example fileExample=new Example(ResourceFilePO.class);
            fileExample.and().andEqualTo("fileKey",saveVO.getAncillaryFileCode());
            ResourceFilePO resourceFilePO=fileDao.selectOneByExample(fileExample);
            if(resourceFilePO==null){
                throw new BusinessException(Type.FAIL.getCode(),"影片编码不存在！");
            }
            wcContentExamineAncillaryPO.setAncillary4Name(resourceFilePO.getFileName());
            wcContentExamineAncillaryPO.setAncillary4Url(resourceFilePO.getFileFullPath());
        }
        wcContentExamineAncillaryDao.insertSelective(wcContentExamineAncillaryPO);
        if(saveVO.getIsOutbox().equals("0")){
            //修改流程
            Example examineExample=new Example(ExaminePO.class);
            examineExample.and().andEqualTo("relatedId",wcContentExaminePO.getId());
            ExaminePO examinePO= examineDao.selectOneByExample(examineExample);
            examinePO.setExamineState(1);
            examinePO.setCreateDate(new Date());
            examinePO.preUpdate();
            examineDao.updateByPrimaryKeySelective(examinePO);
            CompanyInfoPO companyInfoPO=companyInfoDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
            examineService.addExamineLog(new ExamineLogAddVO(examinePO.getRelatedId(), Constants.EXAMINE_LOG_AGREE,Constants.EXAMINE_ONE_NODE,companyInfoPO.getUserName()
                    ,companyInfoPO.getId(),"提交审核",null,null,examinePO.getId()));
        }
    }

    @Override
    public WcContentExamineDetailVO selectWcContentExamineDetailById(String id) {
        WcContentExamineDetailVO examineDetailVO=new WcContentExamineDetailVO();

        WcContentExaminePO wcContentExaminePO=wcContentExamineDao.selectByPrimaryKey(id);
        Example ancillExanole=new Example(WcContentExamineAncillaryPO.class);
        ancillExanole.and().andEqualTo("wcContentExamineId",wcContentExaminePO.getId());
        WcContentExamineAncillaryPO wcContentExamineAncillaryPO=wcContentExamineAncillaryDao.selectOneByExample(ancillExanole);
        BeanUtils.copyProperties(wcContentExaminePO, examineDetailVO);
        BeanUtils.copyProperties(wcContentExamineAncillaryPO, examineDetailVO);


        Example exampleEx=new Example(ExaminePO.class);
        exampleEx.and().andEqualTo("relatedId",id);
        ExaminePO examinePO=examineDao.selectOneByExample(exampleEx);
        examineDetailVO.setFlowId(examinePO.getId());

        return examineDetailVO;
    }

    @Override
    public WcContentExamineDetailVO selectWcContentExamineDetailVOById(String id) {
        ExaminePO examinePO=examineDao.selectByPrimaryKey(id);
        WcContentExamineDetailVO examineDetailVO=new WcContentExamineDetailVO();
        examineDetailVO.setListOne(examineDao.getWcExamineOne(examinePO.getId()));

        examineDetailVO.setFlowId(examinePO.getId());
        WcContentExaminePO wcContentExaminePO=wcContentExamineDao.selectByPrimaryKey(examinePO.getRelatedId());
        Example example=new Example(WcContentExamineAncillaryPO.class);
        example.and().andEqualTo("wcContentExamineId",wcContentExaminePO.getId());
        WcContentExamineAncillaryPO wcContentExamineAncillaryPO=wcContentExamineAncillaryDao.selectOneByExample(example);
        BeanUtils.copyProperties(wcContentExaminePO, examineDetailVO);
        BeanUtils.copyProperties(wcContentExamineAncillaryPO, examineDetailVO);


        Example example2=new Example(CompanyInfoPO.class);
        example2.and().andEqualTo("companyName",examineDetailVO.getUnit());
        CompanyInfoPO companyInfoPO=companyInfoDao.selectOneByExample(example2);
        CulvertApprovalCompanyVo culvertApprovalCompanyVo=new CulvertApprovalCompanyVo();
        culvertApprovalCompanyVo.setCompanyId(companyInfoPO.getId());
        culvertApprovalCompanyVo.setBusinessLicense(companyInfoPO.getBusinessLicense());
        culvertApprovalCompanyVo.setLegalPersonName(companyInfoPO.getUserName());
        culvertApprovalCompanyVo.setLegalPersonPhone(companyInfoPO.getUserPhone());
        culvertApprovalCompanyVo.setCompanyName(companyInfoPO.getCompanyName());
        examineDetailVO.setCompanyVo(culvertApprovalCompanyVo);

        //查询审核记录
        Example example3=new Example(ExamineLogPO.class);
        example3.and().andEqualTo("examineId",examinePO.getId());
        example3.setOrderByClause("examine_date desc");
        List<ExamineLogPO> examineLogPOS=examineLogDao.selectByExample(example3);
        List<ExamineLogVO> examineLogVOList=new ArrayList<>();
        for (ExamineLogPO examineLogPO:examineLogPOS){
            ExamineLogVO examineLogVO=new ExamineLogVO();
            BeanUtils.copyProperties(examineLogPO, examineLogVO);
            examineLogVOList.add(examineLogVO);
        }
        examineDetailVO.setExamineLogList(examineLogVOList);


        //查询提交记录
        List<SubmitLogVO> submitLogVOS=examineDao.getContentExamineSubmitLog(examineDetailVO.getNumber());
        Integer order=0;
        for (SubmitLogVO submitLogVO:submitLogVOS){
            submitLogVO.setSubmitOrder("第"+(submitLogVOS.size()-order)+"次提交");
            order++;
        }
        examineDetailVO.setSubmitLogList(submitLogVOS);


        return examineDetailVO;
    }

    @Override
    public void removeById(IDEntity id) {
        WcContentExaminePO wcContentExaminePO=wcContentExamineDao.selectByPrimaryKey(id);
        examineDao.deleteByPrimaryKey(id.getId());
        Example ancillExanole=new Example(WcContentExamineAncillaryPO.class);
        ancillExanole.and().andEqualTo("wcContentExamineId",wcContentExaminePO.getId());
        wcContentExamineAncillaryDao.deleteByExample(ancillExanole);
        Example example=new Example(ExaminePO.class);
        example.and().andEqualTo("relatedId",wcContentExaminePO.getId()).andEqualTo("examineState",0);
        examineDao.deleteByExample(example);
    }

    @Override
    public  List<WcContentExaminePageListVO> getList(WcContentExamineSelectListDto searchVO) {
        List<WcContentExaminePageListVO> list=examineDao.getWcExamineList(searchVO);
        for (WcContentExaminePageListVO wcContentExaminePageListVO:list){
            Example example=new Example(WcContentExamineAncillaryPO.class);
            example.and().andEqualTo("wcContentExamineId",wcContentExaminePageListVO.getWcId());
            WcContentExamineAncillaryPO wcContentExamineAncillaryPO=wcContentExamineAncillaryDao.selectOneByExample(example);
            List<String> imgList=new ArrayList<>();
            if (wcContentExamineAncillaryPO!=null){
                if(StringUtils.isNotBlank(wcContentExamineAncillaryPO.getAncillary6Url())){
                    imgList.add(wcContentExamineAncillaryPO.getAncillary6Url());
                }
                if(StringUtils.isNotBlank(wcContentExamineAncillaryPO.getAncillary7Url())){
                    imgList.add(wcContentExamineAncillaryPO.getAncillary7Url());
                }
                if(StringUtils.isNotBlank(wcContentExamineAncillaryPO.getAncillary8Url())){
                    imgList.add(wcContentExamineAncillaryPO.getAncillary8Url());
                }
                if(StringUtils.isNotBlank(wcContentExamineAncillaryPO.getAncillary9Url())){
                    imgList.add(wcContentExamineAncillaryPO.getAncillary9Url());
                }
                if(StringUtils.isNotBlank(wcContentExamineAncillaryPO.getAncillary10Url())){
                    imgList.add(wcContentExamineAncillaryPO.getAncillary10Url());
                }
            }
            wcContentExaminePageListVO.setImgs(imgList);
        }
        return list;
    }
    @Autowired
    private UserMessagesDao userMessagesDao;


    @Override
    public void completeTask(ExamineCompleteVO taskCompleteDto) {
        ExaminePO examinePO=examineDao.selectByPrimaryKey(taskCompleteDto.getId());
        if(examinePO==null){
            throw new BusinessException(Type.FAIL.getCode(),"审核信息未找到！");
        }
        if(examinePO.getExamineState()!=1){
            throw new BusinessException(Type.FAIL.getCode(),"流程不是待审核状态，请勿重复操作！");
        }
        SysUserPO sysUserPO=sysUserDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
        if(sysUserPO==null){
            throw new BusinessException(Type.FAIL.getCode(),"用户信息未找到！");
        }
        if(examinePO.getExamineUserIds().indexOf(sysUserPO.getId())<0){
            throw new BusinessException(Type.FAIL.getCode(),"当前用户不是该节点的审批人！");
        }
        String EXAMINE_LOG_AGREE=Constants.EXAMINE_LOG_AGREE;
        String EXAMINE_ONE_NODE=examinePO.getExamineNode();

        CompanyInfoPO companyInfoPO=companyInfoDao.selectByPrimaryKey(examinePO.getCreateBy());
        WcContentExaminePO wcContentExaminePO=wcContentExamineDao.selectByPrimaryKey(examinePO.getRelatedId());

        if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[4])&&taskCompleteDto.getOutcome()==1){
            //初审进入下一阶段
            examinePO.setExamineState(2);
            examinePO.setExamineUserIds("");
            examinePO.setExamineNode(Constants.EXAMINE_MOVIE_LETTER[5]);
            examinePO.preUpdate();
            examineDao.updateByPrimaryKeySelective(examinePO);

            new UserMessageThread(userMessagesDao,"1",
                    "贵单位【"+companyInfoPO.getCompanyName()+"】提交的电影【"+wcContentExaminePO.getMovieName()+"】已获国家电影局公示。在“个人中心-办事记录”中可查看审查决定书电子档，也可联系市电影局（电话：023-63896874)",
                    companyInfoPO.getId()).start();
        }

        if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[3])&&taskCompleteDto.getOutcome()==1){
            //初审进入下一阶段
            examinePO.setExamineState(1);
            examinePO.setExamineUserIds(Constants.EXAMINE_2_USER);
            examinePO.setExamineNode(Constants.EXAMINE_MOVIE_LETTER[4]);
            examinePO.preUpdate();
            examineDao.updateByPrimaryKeySelective(examinePO);

            new UserMessageThread(userMessagesDao,"1",
                    "贵单位【"+companyInfoPO.getCompanyName()+"】提交的电影【"+wcContentExaminePO.getMovieName()+"】已经重庆市电影局审查通过，提交至国家电影局审理，请留意国家电影局官方网站（https://www.chinafilm.gov.cn）的公示通知。",
                    companyInfoPO.getId()).start();

        }
        if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[2])&&taskCompleteDto.getOutcome()==1){
            //审查决定进入下一阶段
            EXAMINE_LOG_AGREE=Constants.EXAMINE_LOG_AGREE_S_P;
            examinePO.setExamineState(1);
            Example example1=new Example(ExamineLogPO.class);
            example1.and().andEqualTo("examineId",examinePO.getId()).andEqualTo("examineUserId",sysUserPO.getId());
            if(examineLogDao.selectCountByExample(example1)>0){
                throw new BusinessException(Type.FAIL.getCode(),"已经评审，请勿重复操作！");
            }
            Example example=new Example(ExamineLogPO.class);
            example.and().andEqualTo("examineId",examinePO.getId()).andEqualTo("examineNode",Constants.EXAMINE_SCRIPT_FILING[2]);
            //评审完毕进入下一阶段
            if( examinePO.getExamineUserIds().split(",").length-1==examineLogDao.selectCountByExample(example)){
                examinePO.setExamineUserIds(Constants.EXAMINE_1_USER);
                examinePO.setExamineNode(Constants.EXAMINE_MOVIE_LETTER[3]);
                examinePO.preUpdate();
                examineDao.updateByPrimaryKeySelective(examinePO);
            }
        }
        if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[1])&&taskCompleteDto.getOutcome()==1){
            //审查决定进入下一阶段
            EXAMINE_LOG_AGREE="受理不指派专家评审";
            examinePO.setExamineState(1);
            examinePO.setExamineUserIds(Constants.EXAMINE_1_USER);
            examinePO.setExamineNode(Constants.EXAMINE_MOVIE_LETTER[3]);
            examinePO.preUpdate();
            examineDao.updateByPrimaryKeySelective(examinePO);
        }

        if(taskCompleteDto.getOutcome()!=1){
            //审核失败  取消流程
            examinePO.setExamineState(taskCompleteDto.getOutcome()+1);
            examinePO.preUpdate();
            EXAMINE_LOG_AGREE=taskCompleteDto.getOutcome()==2?Constants.EXAMINE_LOG_DISAGREE:Constants.EXAMINE_LOG_RETURN;
            examineDao.updateByPrimaryKeySelective(examinePO);

            if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[1])){
                new UserMessageThread(userMessagesDao,"1",
                        "贵单位【"+companyInfoPO.getCompanyName()+"】提交的电影【"+wcContentExaminePO.getMovieName()+"】经审核被退回。请修改后重新提交。",
                        companyInfoPO.getId()).start();
            }
            if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[3])&&taskCompleteDto.getOutcome()==2){
                new UserMessageThread(userMessagesDao,"1",
                        "贵单位【"+companyInfoPO.getCompanyName()+"】提交的电影【"+wcContentExaminePO.getMovieName()+"】经审核未通过。",
                        companyInfoPO.getId()).start();
            }
            if(examinePO.getExamineNode().equals(Constants.EXAMINE_MOVIE_LETTER[3])&&taskCompleteDto.getOutcome()==3){
                new UserMessageThread(userMessagesDao,"1",
                        "贵单位【"+companyInfoPO.getCompanyName()+"】提交的电影【"+wcContentExaminePO.getMovieName()+"】经审核被退回，请修改后重新提交。",
                        companyInfoPO.getId()).start();
            }

        }
        examineService.addExamineLog(new ExamineLogAddVO(examinePO.getRelatedId(), EXAMINE_LOG_AGREE,EXAMINE_ONE_NODE,sysUserPO.getUserName()
                ,sysUserPO.getId(),taskCompleteDto.getComment(),taskCompleteDto.getApprovalFileUrl(),taskCompleteDto.getApprovalFileName(),examinePO.getId()));
    }

    @Autowired
    private SysUserDao sysUserDao;
    @Override
    public void completeTaskUser(ExamineCompleteUserVO taskCompleteDto) {
        ExaminePO examinePO=examineDao.selectByPrimaryKey(taskCompleteDto.getId());
        if(examinePO==null){
            throw new BusinessException(Type.FAIL.getCode(),"审核信息未找到！");
        }
        if(examinePO.getExamineState()!=1){
            throw new BusinessException(Type.FAIL.getCode(),"流程不是待审核状态，请勿重复操作！");
        }
        SysUserPO sysUserPO=sysUserDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
        if(sysUserPO==null){
            throw new BusinessException(Type.FAIL.getCode(),"审核用户信息未找到！");
        }
        if(examinePO.getExamineUserIds().indexOf(sysUserPO.getId())<0){
            throw new BusinessException(Type.FAIL.getCode(),"当前用户不是该节点的审批人！");
        }
        if(taskCompleteDto.getUserIds()==null&&taskCompleteDto.getUserIds().size()==0){
            throw new BusinessException(Type.FAIL.getCode(),"请指派专家信息！");
        }
        StringBuffer userIds=new StringBuffer();
        for (String userId:taskCompleteDto.getUserIds()){
            userIds.append(userId).append(",");
        }
        String EXAMINE_LOG_AGREE="受理并指派专家评审";
        String EXAMINE_ONE_NODE=examinePO.getExamineNode();
        //审查决定进入下一阶段
        examinePO.setExamineState(1);
        examinePO.setExamineUserIds(userIds.substring(0,userIds.length()-1));
        examinePO.setExamineNode(Constants.EXAMINE_MOVIE_LETTER[2]);
        examinePO.preUpdate();
        examineDao.updateByPrimaryKeySelective(examinePO);
        examineService.addExamineLog(new ExamineLogAddVO(examinePO.getRelatedId(), EXAMINE_LOG_AGREE,EXAMINE_ONE_NODE,sysUserPO.getUserName()
                ,sysUserPO.getId(),taskCompleteDto.getComment()==null?"指派专家评审":taskCompleteDto.getComment(),taskCompleteDto.getApprovalFileUrl(),taskCompleteDto.getApprovalFileName(),examinePO.getId()));

    }
}